<?php 
/**
 * payment_address.php
 *
 * Payment management
 *
 * @author     Makai Lajos
 * @copyright  2015
 * @license    License.txt
 * @version    2.0
 * @link       http://opencart-api.com/product/opencart-restful-api-pro-v2-0/
 * @see        http://newapi2.opencart-api.com/demo/
 */
require_once(DIR_SYSTEM . 'engine/restcontroller.php');

class ControllerRestPaymentAddress extends RestController {

	/*
	* Get payment addresses
	*/
   
	public function listPaymentAddresses() {

		$json = array('success' => true);
		
		$this->language->load('checkout/checkout');


		if (isset($this->session->data['payment_address']['address_id'])) {
			$data['address_id'] = $this->session->data['payment_address']['address_id'];
		} else {
			$data['address_id'] = $this->customer->getAddressId();
		}

		$this->load->model('account/address');

        $addresses = array();
        foreach($this->model_account_address->getAddresses() as $address){
            $addresses[] = $address;
        }
        $data['addresses'] = $addresses;

		if (isset($this->session->data['payment_address']['country_id'])) {
			$data['country_id'] = $this->session->data['payment_address']['country_id'];
		} else {
			$data['country_id'] = $this->config->get('config_country_id');
		}

		if (isset($this->session->data['payment_address']['zone_id'])) {
			$data['zone_id'] = $this->session->data['payment_address']['zone_id'];
		} else {
			$data['zone_id'] = '';
		}
		if (isset($this->session->data['payment_address']['city_id'])) {
			$data['city_id'] = $this->session->data['payment_address']['city_id'];
		} else {
			$data['city_id'] = '';
		}


		// Custom Fields
		$this->load->model('account/custom_field');

		$data['custom_fields'] = $this->model_account_custom_field->getCustomFields($this->config->get('config_customer_group_id'));

		if (isset($this->session->data['payment_address']['custom_field'])) {
			$data['payment_address_custom_field'] = $this->session->data['payment_address']['custom_field'];
		} else {
			$data['payment_address_custom_field'] = array();
		}


		if(count($data['addresses']) > 0){
			$json["data"] = $data;
		}else {
			$json["success"]	= false;
			$json["error"]['warning']	= "还没有设置地址";
		}

		if ($this->debugIt) {
			echo '<pre>';
			print_r($json);
			echo '</pre>';
		} else {
			$this->response->setOutput(json_encode($json));
		}			
	}

	/* 
	* Save payment address to database
	*/
	public function savePaymentAddress($post) {

		$this->language->load('checkout/checkout');

		$json = array('success' => true);

		// Validate if customer is logged in.
		if (!$this->customer->isLogged()) {
			$json["error"]['warning']= "用户未登录";
			$json["success"] = false;
		}
        

		// Validate cart has products and has stock.
		if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
			$json["error"]['warning'] = "购物车里还有商品";
			$json["success"] = false;
		}	

		// Validate minimum quantity requirments.			
		$products = $this->cart->getProducts();

		foreach ($products as $product) {
			$product_total = 0;

			foreach ($products as $product_2) {
				if ($product_2['product_id'] == $product['product_id']) {
					$product_total += $product_2['quantity'];
				}
			}		

			if ($product['minimum'] > $product_total) {
				$json['success'] = false;
				$json['error']['warning'] = "产品已经没有库存";

				break;
			}				
		}

		if ($json['success']) {
			if (isset($post['payment_address']) && $post['payment_address'] == 'existing') {
				$this->load->model('account/address');

				if (empty($post['address_id'])) {
					$json['error']['warning'] = $this->language->get('error_address');
					$json['success'] = false;
				} elseif (!in_array($post['address_id'], array_keys($this->model_account_address->getAddresses()))) {
					$json['error']['warning'] = $this->language->get('error_address');
					$json['success'] = false;
				}

				if ($json['success']) {			
				    				// Default Payment Address
					$this->load->model('account/address');

					$this->session->data['payment_address'] = $this->model_account_address->getAddress($post['address_id']);

					unset($this->session->data['payment_method']);
					unset($this->session->data['payment_methods']);
                    
				}
			} else {

        if (!$post['fullname']) {
            $json['error']['warning'] = "收货人姓名不得为空";
            $json['success'] = false;
        }

        if (!preg_match('/^1[0-9]{10}$/', $post['shipping_telephone'])) {
				$json['error']['warning'] ="收货人号码填写有误";
				$json['success'] = false;
			}


        $this->load->model('localisation/country');      
        $country_info = $this->model_localisation_country->getCountry($post['country_id']);

        $this->load->model('localisation/zone');
        $zone_info = $this->model_localisation_zone->getZone($post['zone_id']);

        $this->load->model('localisation/city');
        $city_info = $this->model_localisation_city->getCity($post['city_id']);


        if ((utf8_strlen(trim($post['address'])) < 3) || (utf8_strlen(trim($post['address'])) > 128)) {
            $json['error']['warning'] = "详细地址太短小或者太长";
            $json['success'] = false;
        }


        if ($post['country_id'] == '' || !is_numeric($post['country_id'])) {
            $json['error']['warning'] = "找不到省或市";
            $json['success'] = false;
        }

        if (!isset($post['zone_id']) || $post['zone_id'] == '' || !is_numeric($post['zone_id'])) {
            $json['error']['warning'] = "找不到市或区";
            $json['success'] = false;
        }

         if (!isset($post['city_id']) || $post['city_id'] == '' || !is_numeric($post['city_id'])) {
            $json['error']['warning'] = "找不到信息";
            $json['success'] = false;
        }


				// Custom field validation
				$this->load->model('account/custom_field');

				$custom_fields = $this->model_account_custom_field->getCustomFields($this->config->get('config_customer_group_id'));

				foreach ($custom_fields as $custom_field) {
					if (($custom_field['location'] == 'address') && $custom_field['required'] && empty($post['custom_field'][$custom_field['custom_field_id']])) {
						$json['error']['custom_field' . $custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
						$json['success'] = false;
					}
				}

				if ($json['success']) {
					// Default Payment Address
					$this->load->model('account/address');

					$address_id = $this->model_account_address->addAddress($post);

					$this->session->data['payment_address'] = $this->model_account_address->getAddress($address_id);

					unset($this->session->data['payment_method']);
					unset($this->session->data['payment_methods']);

					$this->load->model('account/activity');

					$activity_data = array(
						'customer_id' => $this->customer->getId(),
						'name'        => $this->customer->getFullname()
					);

					$this->model_account_activity->addActivity('address_add', $activity_data);
				}	
			}		
		}

		if ($this->debugIt) {
			echo '<pre>';
			print_r($json);
			echo '</pre>';
		} else {
			$this->response->setOutput(json_encode($json));
		}	
	}

    
	/*
	* PAYMENT ADDRESS FUNCTIONS
	*/	
	public function paymentaddress() {

		$this->checkPlugin();

		if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
			//get payment addresses
			$this->listPaymentAddresses();
		}else if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
			//save payment address information to session
			$requestjson = file_get_contents('php://input');
		
			$requestjson = json_decode($requestjson, true);           

			if (!empty($requestjson)) {
				$this->savePaymentAddress($requestjson);
			}else {
				$this->response->setOutput(json_encode(array('success' => false)));
			}
		} else if ( $_SERVER['REQUEST_METHOD'] === 'PUT' ){
            $requestjson = file_get_contents('php://input');

            $requestjson = json_decode($requestjson, true);

            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])
                && !empty($requestjson)) {
                $this->editAddress($this->request->get['id'], $requestjson);
            }
        }

    }
}